#include "menu-handler.hh"

MenuHandler::MenuHandler (Window* w)
  : window_size_ (w->width_get (), w->height_get ())
{
  active_menu_ = new DoubleLinkedList<Menu*>;
  unactive_menu_ = new DoubleLinkedList<Menu*>;
}

MenuHandler::~MenuHandler ()
{
  delete active_menu_;
  delete unactive_menu_;
}

void
MenuHandler::add_menu (Menu* m, bool is_active)
{
  if (is_active)
    {
      m->activate ();
      active_menu_->push_front (m);
    }
  else
    unactive_menu_->push_front (m);

  m->set_coord (Vector2d (0, 0), window_size_);
}

void
MenuHandler::delete_menu (Menu* m, bool is_active)
{
  if (is_active)
    active_menu_->erase (m);
  else
    unactive_menu_->erase (m);

  delete m;
}

void
MenuHandler::desactivate (Menu* m)
{
  m->desactivate ();
  active_menu_->erase (m);
  unactive_menu_->push_front (m);
}

void
MenuHandler::activate (Menu* m)
{
  m->activate ();
  unactive_menu_->erase (m);
  active_menu_->push_front (m);
}

void
MenuHandler::update_hoover ()
{
  int x = 0;
  int y = 0;

  SDL_GetMouseState (&x, &y);

  Vector2d cursor (x, y);

  cursor *= 100;
  cursor (0, cursor (0) / window_size_ (0));
  cursor (1, cursor (1) / window_size_ (1));

  LinkedList<Menu*>* parc = active_menu_->end;
  LinkedList<Menu*>* tmp = 0;

  std::list<int>::iterator it;
  bool hoover = false;

  while (parc && !hoover)
    {
      hoover = parc->elt->on_hoover (cursor);

      if (hoover) // si je suis dans le menu et qu'il y a des click souris
	parc->elt->on_hoover (cursor);

      if (hoover)
      	tmp = parc;
      parc = parc->prev;
    }

  if (hoover)
    {
      current_menu_ = tmp->elt;
      current_pos_ = cursor;
      active_menu_->push_back (tmp);
    }
  else
    {
      current_menu_ = 0;
      current_pos_ = Vector2d::zero ();
    }
}

bool
MenuHandler::on_click (unsigned int button_id)
{
  if (current_menu_)
    current_menu_->on_click (current_pos_, button_id);

  return current_menu_;
}

void
MenuHandler::on_release (unsigned int button_id)
{
  if (current_menu_)
    current_menu_->on_release (current_pos_, button_id);
}

void
MenuHandler::dispatch () const
{
  // glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
  LinkedList<Menu*>* parc = active_menu_->begin;

  while (parc)
    {
      parc->elt->dispatch ();
      parc = parc->next;
    }
  // glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
}
